﻿CREATE TRIGGER [tr_Tracker_Car_Insert]
ON [dbo].[t_Tracker_Car] 
FOR INSERT
AS

IF (SELECT COUNT(*) FROM inserted) <
	 (SELECT COUNT(*) FROM t_Tracker_Car AS tc INNER JOIN inserted AS i ON tc.TrackerID = i.TrackerID)
BEGIN
	DECLARE @TrackerID Tracker, @VIN vin
	SELECT @VIN = tc.VIN, @TrackerID = tc.TrackerID FROM t_Tracker_Car AS tc
	INNER JOIN inserted AS i ON tc.TrackerID = i.TrackerID AND tc.VIN <> i.VIN-- AND tc.TrackerID <> i.TrackerID
	ROLLBACK TRAN
	RAISERROR('VIN %s already has installed tracker %s.',16,1,@VIN,@TrackerID)
	RETURN
END

IF EXISTS(SELECT * FROM inserted i INNER JOIN v_LoanInfo l ON l.VIN = i.VIN WHERE DealerSalesPersonID = 0) BEGIN
	ROLLBACK TRAN
	RAISERROR('Dealer must be selected when tracker is being assigned.',16,1)
	RETURN
END

IF EXISTS(SELECT * FROM inserted i WHERE dbo.VinCheck_Installed(VIN)=0) BEGIN
	SELECT @VIN = VIN FROM inserted i WHERE dbo.VinCheck_Installed(VIN)=0
	ROLLBACK TRAN
	RAISERROR('Must have correct 17 digit VIN[%s] before tracker installation.',16,1,@VIN)
	RETURN
END




